<template>
  <div class="shop-page">
    <!-- 商城头部 -->
    <section class="shop-header">
      <div class="container mx-auto px-4 py-6">
        <!-- 顶部导航 -->
        <div class="top-nav flex justify-between items-center mb-6">
          <h1 class="text-2xl font-bold text-gray-900">文创商城</h1>
          <div class="flex items-center gap-4">
            <el-button :icon="ShoppingCart" @click="showCart = true">
              购物车
              <el-badge v-if="cartItemCount" :value="cartItemCount" />
            </el-button>
            <el-button :icon="Star" @click="showFavorites = true">
              我的收藏
              <el-badge v-if="favoriteCount" :value="favoriteCount" />
            </el-button>
          </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-bar flex gap-4">
          <el-input
            v-model="searchQuery"
            placeholder="搜索商品"
            class="search-input flex-1"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 活动专区 -->
      <div class="promotions-section mb-8">
        <h2 class="section-title text-xl font-bold mb-4">活动专区</h2>
        <div class="grid grid-cols-4 gap-4">
          <div
            v-for="promo in promotions"
            :key="promo.id"
            class="promo-card bg-white rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow cursor-pointer"
            @click="handlePromoClick(promo)"
          >
            <el-image
              :src="promo.image"
              class="w-full aspect-[4/3]"
              fit="cover"
            />
            <div class="p-4">
              <h3 class="font-medium mb-2">{{ promo.title }}</h3>
              <p class="text-primary-600 font-bold">{{ promo.subtitle }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="shop-content">
        <!-- 左侧分类导航 -->
        <div class="category-sidebar">
          <h2 class="sidebar-title">商品分类</h2>
          <el-menu
            :default-active="activeCategory"
            class="category-menu"
            @select="handleCategorySelect"
          >
            <el-menu-item
              v-for="category in categories"
              :key="category.id"
              :index="category.id.toString()"
            >
              <el-icon><component :is="category.icon" /></el-icon>
              <span>{{ category.name }}</span>
              <span class="count">({{ category.count }})</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 右侧商品区域 -->
        <div class="products-area">
          <!-- 筛选工具栏 -->
          <div class="filter-toolbar bg-white p-4 rounded-lg shadow-sm mb-6">
            <div class="flex flex-wrap gap-4">
              <!-- 排序选项 -->
              <div class="sort-options">
                <el-radio-group
                  v-model="filterConditions.sortBy"
                  @change="handleSortChange"
                >
                  <el-radio-button
                    v-for="option in sortOptions"
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio-button>
                </el-radio-group>
              </div>

              <!-- 价格区间 -->
              <div class="price-filter">
                <el-select
                  v-model="filterConditions.priceRange"
                  placeholder="价格区间"
                  @change="handlePriceRangeChange"
                  clearable
                >
                  <el-option
                    v-for="range in priceRanges"
                    :key="range.value"
                    :label="range.label"
                    :value="range.value"
                  />
                </el-select>
              </div>

              <!-- 标签筛选 -->
              <div class="tag-filter flex-1">
                <el-select
                  v-model="filterConditions.tags"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  placeholder="商品标签"
                  @change="handleTagsChange"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="tag in tags"
                    :key="tag.value"
                    :label="tag.label"
                    :value="tag.value"
                  />
                </el-select>
              </div>

              <!-- 重置按钮 -->
              <el-button :icon="Refresh" @click="resetFilters">重置</el-button>
            </div>

            <!-- 筛选结果统计 -->
            <div class="filter-summary mt-4 text-gray-500 text-sm">
              找到
              <span class="text-primary-600 font-medium">{{ total }}</span>
              个商品
            </div>
          </div>

          <!-- 商品列表 -->
          <div class="products-grid">
            <div
              v-loading="loading"
              class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-6"
            >
              <ProductCard
                v-for="product in productsList"
                :key="product.id"
                :product="product"
                @favorite="handleFavorite"
                @add-to-cart="handleAddToCart"
                @buy-now="handleBuyNow"
              />
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !productsList.length"
              description="暂无相关商品"
            >
              <el-button @click="resetFilters">清除筛选</el-button>
            </el-empty>

            <!-- 分页 -->
            <div
              v-if="total > 0"
              class="pagination-wrapper flex justify-center mt-8"
            >
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 36, 48]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      size="400px"
      :with-header="false"
    >
      <div class="cart-drawer h-full flex flex-col">
        <div
          class="drawer-header flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700"
        >
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">
            购物车
          </h3>
          <el-button
            v-if="cartItems.length"
            type="danger"
            text
            :icon="Delete"
            @click="handleClearCart"
          >
            清空
          </el-button>
        </div>

        <!-- 购物车列表 -->
        <div
          v-if="cartItems.length"
          class="cart-items flex-1 overflow-y-auto p-4"
        >
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden mb-4 transition-all duration-300 hover:shadow-md"
          >
            <div class="flex p-4 gap-4">
              <div
                class="item-image w-24 h-24 rounded-lg overflow-hidden flex-shrink-0"
              >
                <el-image
                  :src="item.image"
                  :alt="item.title"
                  class="w-full h-full object-cover"
                  fit="cover"
                />
              </div>
              <div class="item-info flex-1 min-w-0">
                <div
                  class="item-name text-gray-900 dark:text-white font-medium mb-2 line-clamp-2 hover:text-primary-600 transition-colors"
                >
                  {{ item.title }}
                </div>
                <div class="item-price flex items-center justify-between">
                  <span
                    class="price text-primary-600 dark:text-primary-400 font-semibold"
                  >
                    ¥{{ formatPrice(item.price) }}
                  </span>
                  <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    :max="item.stock || 99"
                    size="small"
                    @change="handleQuantityChange(item)"
                  />
                </div>
              </div>
              <el-button
                class="remove-button text-gray-400 hover:text-red-500 transition-colors"
                type="text"
                :icon="Close"
                @click="handleRemoveFromCart(item)"
              />
            </div>
          </div>
        </div>

        <!-- 空购物车状态 -->
        <el-empty v-else description="暂无购物商品">
          <el-button type="primary" @click="showCart = false">
            去逛逛
          </el-button>
        </el-empty>

        <!-- 购物车底部 -->
        <div
          v-if="cartItems.length"
          class="cart-footer bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4"
        >
          <div class="total-price flex items-center justify-between mb-4">
            <span class="label text-gray-600 dark:text-gray-400">合计:</span>
            <span
              class="amount text-xl font-bold text-primary-600 dark:text-primary-400"
            >
              ¥{{ formatPrice(totalPrice) }}
            </span>
          </div>
          <el-button
            type="primary"
            class="checkout-button w-full h-12 text-lg font-medium"
            :loading="checkoutLoading"
            @click="handleCheckout"
          >
            结算 ({{ cartItemCount }}件)
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 收藏夹抽屉 -->
    <el-drawer v-model="showFavorites" title="我的收藏" size="400px" :with-header="false">
      <div class="favorites-drawer h-full flex flex-col">
        <div
          class="drawer-header flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700"
        >
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">
            我的收藏
          </h3>
        </div>

        <div
          v-if="favoriteItems.length"
          class="favorite-items flex-1 overflow-y-auto p-4 space-y-4"
        >
          <div
            v-for="item in favoriteItems"
            :key="item.id"
            class="favorite-item bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md"
          >
            <div class="flex p-4 gap-4">
              <div
                class="item-image w-24 h-24 rounded-lg overflow-hidden flex-shrink-0"
              >
                <el-image
                  :src="item.image"
                  :alt="item.title"
                  class="w-full h-full object-cover"
                  fit="cover"
                />
              </div>
              <div class="item-info flex-1 min-w-0">
                <div
                  class="item-name text-gray-900 dark:text-white font-medium mb-2 line-clamp-2 hover:text-primary-600 transition-colors"
                >
                  {{ item.title }}
                </div>
                <div class="item-price text-lg font-bold text-primary-600 dark:text-primary-400">
                  ¥{{ formatPrice(item.price) }}
                </div>
              </div>
              <div class="item-actions flex flex-col gap-2">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleAddToCart(item)"
                >
                  加入购物车
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleRemoveFavorite(item)"
                >
                  取消收藏
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <el-empty v-else class="mt-16" description="暂无收藏商品">
          <el-button type="primary" @click="showFavorites = false">
            去逛逛
          </el-button>
        </el-empty>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user";
import service from "@/api/axios"; // 导入axios服务
import {
  Search,
  Grid,
  List,
  Delete,
  Close,
  ShoppingBag,
  Present,
  Food,
  Goods,
  Collection,
  ShoppingCart,
  Star,
  Refresh,
} from "@element-plus/icons-vue";
import ProductCard from "@/components/shop/ProductCard.vue";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);

// 激活的分类
const activeCategory = ref("0");

// 搜索和筛选条件
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 筛选条件
const filterConditions = reactive({
  category: "",
  priceRange: "",
  tags: [],
  sortBy: "default",
  minPrice: null,
  maxPrice: null,
});

// 价格区间选项
const priceRanges = [
  { label: "全部", value: "" },
  { label: "0-99元", value: "0-99" },
  { label: "100-299元", value: "100-299" },
  { label: "300-499元", value: "300-499" },
  { label: "500-999元", value: "500-999" },
  { label: "1000元以上", value: "1000+" },
];

// 商品标签
const tags = ref([]);

// 排序选项
const sortOptions = [
  { label: "默认排序", value: "default" },
  { label: "销量优先", value: "sales" },
  { label: "价格从低到高", value: "price-asc" },
  { label: "价格从高到低", value: "price-desc" },
  { label: "好评优先", value: "rating" },
  { label: "最新上架", value: "newest" },
];

// 分类数据
const categories = ref([]);

// 商品数据
const productsList = ref([]);

// 购物车相关
const showCart = ref(false);
const cartItems = ref([]);
const checkoutLoading = ref(false);

// 计算购物车商品数量
const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0);
});

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
});

// 收藏相关
const showFavorites = ref(false);
const favoriteItems = ref([]);
const favoriteCount = computed(() => favoriteItems.value.length);

// 活动专区数据
const promotions = ref([
  {
    id: 1,
    title: "新人专享",
    subtitle: "首单立减50元",
    image:
      "https://img1.baidu.com/it/u=2713556423,3098640978&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1082",
    link: "/promotions/new-user",
  },
  {
    id: 2,
    title: "限时秒杀",
    subtitle: "低至5折",
    image:
      "https://img2.baidu.com/it/u=115387460,1877966775&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500",
    link: "/promotions/flash-sale",
  },
  {
    id: 3,
    title: "文创套装",
    subtitle: "套装85折",
    image:
      "https://img1.baidu.com/it/u=2569960121,1531607229&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=688",
    link: "/promotions/bundle",
  },
  {
    id: 4,
    title: "会员专享",
    subtitle: "积分双倍",
    image:
      "https://img1.baidu.com/it/u=3832233862,3427702156&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
    link: "/promotions/vip",
  },
]);

// 检查登录状态
const checkLogin = async () => {
  if (!userStore.token) {
    try {
      await ElMessageBox.confirm("登录后才能继续操作，是否前往登录？", "提示", {
        confirmButtonText: "去登录",
        cancelButtonText: "取消",
        type: "warning",
      });
      router.push({
        path: "/login",
        query: { redirect: router.currentRoute.value.fullPath },
      });
      return false;
    } catch {
      return false;
    }
  }
  return true;
};

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await service.get("/public/shop/categories");
    if (response && response.data && Array.isArray(response.data)) {
      categories.value = response.data;
    } else {
      // 使用测试数据
      categories.value = [
        {
          id: 0,
          name: "全部商品",
          icon: "Goods",
          count: 235,
        },
        {
          id: 1,
          name: "手工艺品",
          icon: "Present",
          count: 68,
        },
        {
          id: 2,
          name: "特色美食",
          icon: "Food",
          count: 45,
        },
        {
          id: 3,
          name: "文创用品",
          icon: "Collection",
          count: 122,
        },
      ];
    }
  } catch (error) {
    console.error("获取分类失败:", error);
    // 使用测试数据
    categories.value = [
      {
        id: 0,
        name: "全部商品",
        icon: "Goods",
        count: 235,
      },
      {
        id: 1,
        name: "手工艺品",
        icon: "Present",
        count: 68,
      },
      {
        id: 2,
        name: "特色美食",
        icon: "Food",
        count: 45,
      },
      {
        id: 3,
        name: "文创用品",
        icon: "Collection",
        count: 122,
      },
    ];
  }
};

// 获取标签数据
const fetchTags = async () => {
  try {
    const response = await service.get("/public/shop/tags");
    if (response && response.data && Array.isArray(response.data)) {
      tags.value = response.data;
    } else {
      // 使用测试数据
      tags.value = [
        { label: "新品上市", value: "new" },
        { label: "限时促销", value: "sale" },
        { label: "精选推荐", value: "featured" },
        { label: "热销爆款", value: "hot" },
        { label: "库存告急", value: "low_stock" },
      ];
    }
  } catch (error) {
    console.error("获取标签失败:", error);
    // 使用测试数据
    tags.value = [
      { label: "新品上市", value: "new" },
      { label: "限时促销", value: "sale" },
      { label: "精选推荐", value: "featured" },
      { label: "热销爆款", value: "hot" },
      { label: "库存告急", value: "low_stock" },
    ];
  }
};

// 处理筛选
const handleFilter = async () => {
  loading.value = true;
  try {
    // 构建过滤条件但不包含分页参数
    const params = {
      ...filterConditions,
      search: searchQuery.value,
    };

    const response = await service.get("/public/shop/products", { params });
    
    let allProducts = [];
    
    if (response && response.data && Array.isArray(response.data)) {
      // 服务器返回的数据在 data 字段中
      allProducts = response.data;
      total.value = response.data.length;
    } else if (response && response.data && response.data.items && Array.isArray(response.data.items)) {
      // 服务器返回了带items字段的数据
      allProducts = response.data.items;
      total.value = response.data.total || response.data.items.length;
    } else {
      // 使用测试数据
      allProducts = [
        {
          id: 1,
          title: "贵港特色手工艺品",
          price: 299,
          image:
            "https://img2.baidu.com/it/u=3987350406,887830238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
          sales: 100,
          rating: 4.8,
          reviewCount: 56,
          tags: ["新品", "热销"],
          isFavorite: false,
        },
        {
          id: 2,
          title: "贵港陶瓷工艺品",
          price: 199,
          image:
            "https://img1.baidu.com/it/u=2569960121,1531607229&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=688",
          sales: 85,
          rating: 4.5,
          reviewCount: 42,
          tags: ["热销"],
          isFavorite: false,
        },
        {
          id: 3,
          title: "特色竹编工艺",
          price: 159,
          image:
            "https://img2.baidu.com/it/u=115387460,1877966775&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500",
          sales: 65,
          rating: 4.7,
          reviewCount: 38,
          tags: ["新品", "限量"],
          isFavorite: false,
        }
      ];
      total.value = allProducts.length;
    }
    
    // 前端进行分页
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    productsList.value = allProducts.slice(startIndex, endIndex);
    
  } catch (error) {
    console.error("获取商品列表失败:", error);
    // 使用测试数据
    const testProducts = [
      {
        id: 1,
        title: "贵港特色手工艺品",
        price: 299,
        image:
          "https://img2.baidu.com/it/u=3987350406,887830238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
        sales: 100,
        rating: 4.8,
        reviewCount: 56,
        tags: ["新品", "热销"],
        isFavorite: false,
      },
      {
        id: 2,
        title: "贵港陶瓷工艺品",
        price: 199,
        image:
          "https://img1.baidu.com/it/u=2569960121,1531607229&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=688",
        sales: 85,
        rating: 4.5,
        reviewCount: 42,
        tags: ["热销"],
        isFavorite: false,
      },
      {
        id: 3,
        title: "特色竹编工艺",
        price: 159,
        image:
          "https://img2.baidu.com/it/u=115387460,1877966775&fm=253&fmt=auto&app=138&f=PNG?w=500&h=500",
        sales: 65,
        rating: 4.7,
        reviewCount: 38,
        tags: ["新品", "限量"],
        isFavorite: false,
      }
    ];
    total.value = testProducts.length;
    
    // 前端进行分页
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    productsList.value = testProducts.slice(startIndex, endIndex);
  } finally {
    loading.value = false;
  }
};

// 处理价格区间变化
const handlePriceRangeChange = (range) => {
  if (!range) {
    filterConditions.minPrice = null;
    filterConditions.maxPrice = null;
  } else if (range === "1000+") {
    filterConditions.minPrice = 1000;
    filterConditions.maxPrice = null;
  } else {
    const [min, max] = range.split("-").map(Number);
    filterConditions.minPrice = min;
    filterConditions.maxPrice = max;
  }
  handleFilter();
};

// 处理排序变化
const handleSortChange = (value) => {
  filterConditions.sortBy = value;
  handleFilter();
};

// 处理标签变化
const handleTagsChange = (values) => {
  filterConditions.tags = values;
  handleFilter();
};

// 处理分类选择
const handleCategorySelect = (categoryId) => {
  activeCategory.value = categoryId;
  filterConditions.category = categoryId;
  handleFilter();
};

// 重置筛选条件
const resetFilters = () => {
  Object.assign(filterConditions, {
    category: "",
    priceRange: "",
    tags: [],
    sortBy: "default",
    minPrice: null,
    maxPrice: null,
  });
  searchQuery.value = "";
  currentPage.value = 1;
  activeCategory.value = "0";
  handleFilter();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  handleFilter();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  handleFilter();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleFilter();
};

// 监听筛选条件变化
watch(
  filterConditions,
  () => {
    currentPage.value = 1;
    handleFilter();
  },
  { deep: true },
);

// 页面加载时获取数据
onMounted(() => {
  fetchCategories();
  fetchTags();
  handleFilter();
});

// 处理活动点击
const handlePromoClick = (promo) => {
  router.push(promo.link);
};

// 处理收藏
const handleFavorite = async (product) => {
  if (!(await checkLogin())) return;

  try {
    const response = await service.post("/shop/favorites/toggle", { productId: product.id });
    if (response && response.data) {
      ElMessage.success(product.isFavorite ? "已取消收藏" : "收藏成功");
      product.isFavorite = !product.isFavorite;
      // 如果当前显示收藏夹，刷新收藏列表
      if (showFavorites.value) {
        getFavoriteList();
      }
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理加入购物车
const handleAddToCart = async (product) => {
  if (!(await checkLogin())) return;

  try {
    const response = await service.post("/shop/cart/add", { 
      productId: product.id,
      quantity: 1
    });
    
    if (response && response.data) {
      ElMessage.success("已添加到购物车");
      // 刷新购物车数据
      getCartList();
      // 显示购物车抽屉
      showCart.value = true;
    }
  } catch (error) {
    console.error("添加购物车失败:", error);
    
    // 如果接口失败，使用本地逻辑添加
    const existingItem = cartItems.value.find((item) => item.id === product.id);
    if (existingItem) {
      existingItem.quantity += 1;
      ElMessage.success("已增加商品数量");
    } else {
      cartItems.value.push({
        ...product,
        quantity: 1,
      });
      ElMessage.success("已添加到购物车");
    }
    showCart.value = true;
  }
};

// 处理立即购买
const handleBuyNow = async (product) => {
  if (!(await checkLogin())) return;

  router.push({
    path: "/order/confirm",
    query: {
      productId: product.id,
      quantity: 1,
      type: "buy_now",
    },
  });
};

// 获取购物车列表
const getCartList = async () => {
  try {
    const response = await service.get("/shop/cart/list");
    if (response && response.data && Array.isArray(response.data)) {
      cartItems.value = response.data;
    }
  } catch (error) {
    console.error("获取购物车失败:", error);
    // 保留现有购物车数据，不清空
  }
};

// 处理从购物车移除
const handleRemoveFromCart = async (item) => {
  try {
    const response = await service.post("/shop/cart/remove", { 
      productId: item.id 
    });
    
    if (response && response.data) {
      const index = cartItems.value.findIndex((i) => i.id === item.id);
      if (index > -1) {
        cartItems.value.splice(index, 1);
        ElMessage.success("已从购物车移除");
      }
    }
  } catch (error) {
    console.error("从购物车移除失败:", error);
    // 本地移除
    const index = cartItems.value.findIndex((i) => i.id === item.id);
    if (index > -1) {
      cartItems.value.splice(index, 1);
      ElMessage.success("已从购物车移除");
    }
  }
};

// 处理清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm("确定要清空购物车吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    const response = await service.post("/shop/cart/clear");
    if (response && response.data) {
      cartItems.value = [];
      ElMessage.success("购物车已清空");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("清空购物车失败:", error);
      // 如果API失败但用户已确认，本地清空
      if (cartItems.value.length > 0) {
        cartItems.value = [];
        ElMessage.success("购物车已清空");
      }
    }
  }
};

// 处理数量变化
const handleQuantityChange = async (item) => {
  // 确保数量在有效范围内
  if (item.quantity < 1) {
    item.quantity = 1;
  }
  if (item.stock && item.quantity > item.stock) {
    item.quantity = item.stock;
    ElMessage.warning(`该商品库存只有 ${item.stock} 件`);
  }
  
  try {
    await service.post("/shop/cart/update", {
      productId: item.id,
      quantity: item.quantity
    });
  } catch (error) {
    console.error("更新购物车数量失败:", error);
    // 保留本地数量变更
  }
};

// 处理结算
const handleCheckout = async () => {
  if (!cartItems.value.length) {
    ElMessage.warning("购物车是空的");
    return;
  }

  checkoutLoading.value = true;
  try {
    const response = await service.post("/shop/order/create-from-cart");
    if (response && response.data && response.data.orderId) {
      router.push({
        path: "/order/confirm",
        query: { orderId: response.data.orderId }
      });
    } else {
      // 模拟成功结算
      router.push({
        path: "/order/confirm",
        query: { type: "cart" }
      });
    }
  } catch (error) {
    console.error("结算失败:", error);
    ElMessage.error("结算失败，请重试");
  } finally {
    checkoutLoading.value = false;
  }
};

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2);
};

// 获取收藏列表
const getFavoriteList = async () => {
  try {
    const response = await service.get("/shop/favorites/list");
    if (response && response.data && Array.isArray(response.data)) {
      favoriteItems.value = response.data;
    } else {
      // 使用测试数据
      favoriteItems.value = [
        {
          id: 1,
          title: "贵港特色手工艺品",
          price: 299,
          image: "https://img2.baidu.com/it/u=3987350406,887830238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
        }
      ];
    }
  } catch (error) {
    console.error("获取收藏列表失败:", error);
    // 使用测试数据
    favoriteItems.value = [
      {
        id: 1,
        title: "贵港特色手工艺品",
        price: 299,
        image: "https://img2.baidu.com/it/u=3987350406,887830238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
      }
    ];
  }
};

// 处理取消收藏
const handleRemoveFavorite = async (item) => {
  try {
    const response = await service.post("/shop/favorites/toggle", { productId: item.id });
    if (response && response.data) {
      const index = favoriteItems.value.findIndex((i) => i.id === item.id);
      if (index > -1) {
        favoriteItems.value.splice(index, 1);
        ElMessage.success("已取消收藏");
      }
    }
  } catch (error) {
    console.error("取消收藏失败:", error);
    // 本地移除
    const index = favoriteItems.value.findIndex((i) => i.id === item.id);
    if (index > -1) {
      favoriteItems.value.splice(index, 1);
      ElMessage.success("已取消收藏");
    }
  }
};

// 监听抽屉显示状态
watch(showFavorites, (val) => {
  if (val) {
    getFavoriteList();
  }
});

watch(showCart, (val) => {
  if (val) {
    getCartList();
  }
});
</script>

<style lang="scss" scoped>
.shop-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .shop-header {
    @apply bg-white dark:bg-gray-800 shadow-sm relative mb-6;

    h1 {
      @apply text-gray-900 dark:text-white;
    }

    .container {
      @apply relative;
    }

    .search-bar {
      @apply max-w-2xl mx-auto;

      .search-input {
        :deep(.el-input__wrapper) {
          height: 42px;
          border: 1px solid #dcdfe6;
          border-radius: 8px;
          transition: all 0.3s ease;
          box-shadow: none;

          &:hover {
            border-color: #409eff;
          }

          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2);
          }
        }

        :deep(.el-input__inner) {
          height: 42px;
          line-height: 42px;
        }

        :deep(.el-input__prefix) {
          color: #909399;
          font-size: 18px;
          transition: color 0.3s ease;
        }

        &:hover {
          :deep(.el-input__prefix) {
            color: #409eff;
          }
        }
      }

      :deep(.el-button) {
        height: 42px;
        padding: 11px 20px;
        border-radius: 8px;
        transition: all 0.3s ease;
      }
    }
  }

  .promotions-section {
    .section-title {
      @apply text-gray-900 dark:text-white;
    }

    .promo-card {
      @apply cursor-pointer transition-all duration-300 bg-white dark:bg-gray-800 
             border border-gray-200 dark:border-gray-700
             shadow-[0_2px_12px_0_rgba(0,0,0,0.1)] dark:shadow-[0_2px_12px_0_rgba(0,0,0,0.3)];

      &:hover {
        @apply transform -translate-y-1 
               shadow-[0_4px_20px_0_rgba(0,0,0,0.15)] dark:shadow-[0_4px_20px_0_rgba(0,0,0,0.4)]
               border-gray-300 dark:border-gray-600;
      }

      h3 {
        @apply text-gray-900 dark:text-white;
      }

      p {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }

  .shop-content {
    @apply flex gap-6;

    .category-sidebar {
      @apply w-60 flex-shrink-0;

      .sidebar-title {
        @apply text-lg font-bold mb-4 text-gray-900 dark:text-white;
      }

      :deep(.el-menu) {
        @apply bg-transparent border-0 rounded-lg;

        .el-menu-item {
          @apply mb-1 rounded-lg text-gray-700 dark:text-gray-300;

          &:hover,
          &.is-active {
            @apply bg-primary-50 dark:bg-primary-900/50;
          }

          .count {
            @apply ml-auto text-sm text-gray-500 dark:text-gray-400;
          }
        }
      }
    }

    .products-area {
      @apply flex-1;

      .filter-toolbar {
        @apply bg-white dark:bg-gray-800 p-4 rounded-lg 
               border border-gray-200 dark:border-gray-700
               shadow-[0_2px_12px_0_rgba(0,0,0,0.1)] dark:shadow-[0_2px_12px_0_rgba(0,0,0,0.3)];

        .filter-summary {
          @apply text-gray-500 dark:text-gray-400;

          span {
            @apply text-primary-600 dark:text-primary-400;
          }
        }
      }

      .products-grid {
        @apply relative min-h-[200px];
      }
    }
  }

  // 响应式设计
  @media (max-width: 1024px) {
    .shop-content {
      @apply flex-col;

      .category-sidebar {
        @apply w-full mb-6;
      }
    }
  }

  @media (max-width: 640px) {
    .filter-toolbar {
      .sort-options {
        @apply w-full mb-4;
      }

      .filter-options {
        @apply flex-wrap;

        :deep(.el-select) {
          @apply w-full;
        }
      }
    }
  }

  // 购物车样式
  .cart-drawer {
    .cart-item {
      .item-image {
        img {
          @apply transition-transform duration-300;
        }

        &:hover img {
          @apply scale-110;
        }
      }

      .item-name {
        &:hover {
          @apply cursor-pointer;
        }
      }

      .el-input-number {
        @apply w-24;
      }
    }

    .empty-cart {
      .el-icon {
        @apply opacity-50;
      }
    }

    .cart-footer {
      .checkout-button {
        @apply rounded-lg;
      }
    }
  }
}

// 加载动画
.loading-skeleton {
  @apply animate-pulse bg-gray-200 dark:bg-gray-700 rounded;
}

.favorites-drawer {
  .favorite-items {
    .favorite-item {
      @apply transition-transform duration-300 border border-gray-100 dark:border-gray-700;
      
      &:hover {
        @apply transform -translate-y-1 shadow-md;
        
        .item-image img {
          @apply scale-110;
        }
      }

      .item-image {
        img {
          @apply transition-transform duration-300;
        }
      }

      .item-name {
        &:hover {
          @apply cursor-pointer;
        }
      }
    }
  }
}
</style>
